from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer
from django.conf import settings


def dumps(data, expires):
    # 创建对象,(秘钥, 有效期秒)
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires)
    # 将字典加密,返回bytes类型,故decode()
    result = serializer.dumps(data).decode()

    return result


def loads(data, expires):
    # 创建对象
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires)
    # 将字符串解密成字典
    try:
        data_dict = serializer.loads(data)
        return data_dict
    except BadData:
        # 抛异常的原因：超时
        return None
